package com.tangyuan.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;
import java.util.Date;

@Data
public class OSSUtilBase64 {

    private static final String ENDPOINT = "oss-cn-qingdao.aliyuncs.com";   // 阿里云 OSS 外网或内网地址
    private static final String ACCESS_KEY_ID = "LTAI5tQZMYYEwFYBC8vYCkPR";  // 阿里云账号 AccessKeyId
    private static final String ACCESS_KEY_SECRET = "FKqXvgNCC5ivMFLcqZHh0TXF7u0iyF";  // 阿里云账号 AccessKeySecret
    private static final String BUCKET_NAME = "shengtangfeng1";  // 存储空间名称

    public static String uploadBase64String(String base64String, String objectName) throws IOException {
        byte[] decodedBytes = Base64.getDecoder().decode(base64String);

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 创建一个ByteArrayInputStream对象
            InputStream inputStream = new ByteArrayInputStream(decodedBytes);

            // 创建ObjectMetadata对象，并设置content length
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(decodedBytes.length);

            // 上传文件流
            ossClient.putObject(BUCKET_NAME, objectName, inputStream, metadata);

            // 设置Bucket为公共读
            ossClient.setBucketAcl(BUCKET_NAME, com.aliyun.oss.model.CannedAccessControlList.PublicRead);

            // 构建文件的URL
            String url = "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + objectName;

            return url;
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
}

